#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int ticket = 100;//一百张票
pthread_mutex_t mutex;//定义一个锁
void *scalpers(void *arg)
{
    while(1) {
        pthread_mutex_lock(&mutex);//加锁
        if (ticket > 0) {
            usleep(10);
            printf("scalper:%d------get tickets:%d\n", (int)arg, ticket);
            ticket--;
            pthread_mutex_unlock(&mutex);//解锁
        }else {
            printf("scalper:%d------complete the mission\n", (int)arg);
            pthread_mutex_unlock(&mutex);//在任意可能退出的位置前解锁
            pthread_exit(NULL);//退出线程
        }
        usleep(1);
    }
}
int main()
{
    pthread_t tid[4];
    int ret;
    pthread_mutex_init(&mutex, NULL);//初始化锁资源
    for(int i = 0; i < 4; i++) {//创建4个线程
        ret = pthread_create(&tid[i], NULL, scalpers, (void*)i); 
        if(ret != 0) {
            printf("create thread error\n");
            return -1;
        }
    }
    for (int i = 0; i < 4; i++) {//等待4个线程退出
        pthread_join(tid[i], NULL);
    }
    pthread_mutex_destroy(&mutex);//销毁锁资源
    return 0;
}
